package logrus_config


import (
	"github.com/sirupsen/logrus"
	"time"
	"github.com/pkg/errors"
	"path"
	"github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"os"
	"fmt"
	"bufio"
)

func ConfigLocalFileSystemLogger(logPath,logFileName,level string) {
	basePath := path.Join(logPath,logFileName)
	writer, e := rotatelogs.New(
		basePath+".%Y%m%d",
		rotatelogs.WithMaxAge(-1),     				// 在被文件系统清除之前 文件最大的保存时间 MaxAge should be disabled by specifing WithMaxAge(-1) explicitly.
		rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),	// 这个是切割日志的时间 一天切一次
	)
	if e != nil {
		logrus.Errorf("config local file system logger error. %+v", errors.WithStack(e))
	}
	// 日志日志等级不是debug 就不输出到控制台
	switch level {
	case "debug":
		logrus.SetLevel(logrus.DebugLevel)
		logrus.SetOutput(os.Stderr)
	case "info":
		setNull()
		logrus.SetLevel(logrus.InfoLevel)
	case "warn":
		setNull()
		logrus.SetLevel(logrus.WarnLevel)
	case "error":
		setNull()
		logrus.SetLevel(logrus.ErrorLevel)
	default:
		setNull()
		logrus.SetLevel(logrus.InfoLevel)
	}
	lfHook := lfshook.NewHook(lfshook.WriterMap{
		logrus.DebugLevel	: writer, // 为不同级别设置不同的输出目的
		logrus.InfoLevel		: writer,
		logrus.WarnLevel		: writer,
		logrus.ErrorLevel		: writer,
		logrus.FatalLevel		: writer,
		logrus.PanicLevel		: writer,
	},&logrus.JSONFormatter{TimestampFormat:"2006-01-02 15:04:05"})
	logrus.AddHook(lfHook)
}
func setNull() {
	src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	if err!= nil{
		fmt.Println("err", err)
	}
	writer := bufio.NewWriter(src)
	logrus.SetOutput(writer)
}